package com.mingte.manghe.controller;

import com.mingte.manghe.dto.TeaUserDTO;
import com.mingte.manghe.exception.UserNotExistExecption;
import com.mingte.manghe.utils.JwtUtils;
import com.mingte.manghe.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

public class BaseController {

    protected static int reqCount = 0;


    @Autowired
    protected RedisUtils redisUtils;


    protected TeaUserDTO getTeaUser() throws UserNotExistExecption {

        ++reqCount;

        RequestAttributes requestAttributes = RequestContextHolder
                .currentRequestAttributes();
        ServletRequestAttributes attributes = (ServletRequestAttributes) requestAttributes;
        HttpServletRequest request = attributes.getRequest();

        String token = request.getHeader("access_mh_token");
        boolean b = JwtUtils.checkSign(token);

        String userId = JwtUtils.getUserId(token);
        Object o = redisUtils.get(userId);

        if(b && null != o){
            return (TeaUserDTO)o;
        }else{
            throw new UserNotExistExecption("登录时间已过期,请重新登录");
        }
    }
}
